<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拼多多 - 手写MyBatis：渐进式源码实践</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
        }

        body {
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.5;
        }

        .container {
            max-width: 750px;
            margin: 0 auto;
            background-color: #fff;
            position: relative;
            min-height: 100vh;
        }

        /* 轮播图样式 */
        .swiper-container {
            position: relative;
            width: 100%;
            height: 375px;
            overflow: hidden;
            background-color: #f8f8f8;
        }

        .swiper-wrapper {
            display: flex;
            transition: transform 0.3s ease;
        }

        .swiper-slide {
            flex: 0 0 100%;
            height: 375px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .swiper-slide img {
            max-width: 100%;
            max-height: 100%;
        }

        .swiper-indicator {
            position: absolute;
            bottom: 10px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 5px;
        }

        .swiper-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.5);
        }

        .swiper-dot.active {
            background-color: #fff;
        }

        /* 商品信息样式 */
        .product-info {
            padding: 15px;
            background-color: #fff;
        }

        .product-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            line-height: 1.4;
        }

        .promotion {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .promotion-tag {
            background-color: #ff3b30;
            color: white;
            font-size: 12px;
            padding: 2px 5px;
            border-radius: 2px;
            margin-right: 8px;
        }

        .promotion-text {
            font-size: 14px;
            color: #ff3b30;
        }

        .price-section {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .current-price {
            font-size: 24px;
            color: #ff3b30;
            font-weight: bold;
        }

        .original-price {
            font-size: 14px;
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }

        /* 拼团信息样式 */
        .group-buy-section {
            background-color: #fff;
            margin-top: 10px;
            padding: 15px;
        }

        .section-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
        }

        .group-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .group-item {
            display: flex;
            align-items: center;
            padding: 12px;
            background-color: #f8f8f8;
            border-radius: 8px;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #ff3b30;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
            margin-right: 12px;
        }

        .group-info {
            flex: 1;
        }

        .group-name {
            font-size: 14px;
            margin-bottom: 4px;
        }

        .group-status {
            font-size: 12px;
            color: #ff3b30;
        }

        .group-action {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }

        .countdown {
            font-size: 14px;
            color: #ff3b30;
            margin-bottom: 5px;
        }

        .join-btn {
            background-color: #ff3b30;
            color: white;
            border: none;
            padding: 6px 15px;
            border-radius: 15px;
            font-size: 14px;
            cursor: pointer;
        }

        /* 底部操作栏 */
        .bottom-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: #fff;
            display: flex;
            height: 50px;
            border-top: 1px solid #eee;
            z-index: 100;
        }

        .action-btn {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #666;
            background-color: #fff;
            border: none;
            cursor: pointer;
        }

        .action-btn .icon {
            font-size: 18px;
            margin-bottom: 2px;
        }

        .buy-btns {
            display: flex;
            flex: 2;
        }

        .solo-buy {
            flex: 1;
            background-color: #ff9500;
            color: white;
            border: none;
            font-size: 16px;
            cursor: pointer;
        }

        .group-buy {
            flex: 1;
            background-color: #ff3b30;
            color: white;
            border: none;
            font-size: 16px;
            cursor: pointer;
        }

        /* 支付页面样式 */
        .payment-page {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #fff;
            z-index: 200;
            padding: 20px;
            flex-direction: column;
            align-items: center;
        }

        .payment-header {
            width: 100%;
            text-align: center;
            padding: 15px 0;
            font-size: 18px;
            font-weight: bold;
            border-bottom: 1px solid #eee;
            margin-bottom: 30px;
        }

        .payment-amount {
            font-size: 24px;
            color: #ff3b30;
            margin-bottom: 30px;
        }

        .qrcode-container {
            width: 250px;
            height: 250px;
            background-color: #f8f8f8;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30px;
            border-radius: 8px;
        }

        .qrcode-placeholder {
            text-align: center;
            color: #999;
        }

        .payment-actions {
            display: flex;
            gap: 20px;
        }

        .cancel-btn {
            padding: 10px 30px;
            background-color: #f8f8f8;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }

        .confirm-btn {
            padding: 10px 30px;
            background-color: #ff3b30;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        /* 登录弹窗样式 - 添加前缀 */
        .login-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 250;
            justify-content: center;
            align-items: center;
        }

        .login-container {
            width: 90%;
            max-width: 400px;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            animation: login-popup 0.3s ease-out;
            position: relative;
        }

        @keyframes login-popup {
            0% {
                transform: scale(0.8);
                opacity: 0;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .login-header {
            background: linear-gradient(135deg, #ff3b30, #ff6b6b);
            color: white;
            padding: 25px 20px;
            text-align: center;
        }

        .login-title {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 8px;
        }

        .login-subtitle {
            font-size: 14px;
            opacity: 0.9;
        }

        .login-form {
            padding: 25px;
        }

        .login-form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .login-form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            color: #666;
            font-weight: 500;
        }

        .login-form-input {
            width: 100%;
            padding: 14px 16px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s;
        }

        .login-form-input:focus {
            border-color: #ff3b30;
            outline: none;
            box-shadow: 0 0 0 2px rgba(255, 59, 48, 0.1);
        }

        .login-form-error {
            color: #ff3b30;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .login-btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #ff3b30, #ff6b6b);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 10px;
            box-shadow: 0 4px 8px rgba(255, 59, 48, 0.2);
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(255, 59, 48, 0.3);
        }

        .login-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(255, 59, 48, 0.2);
        }

        .login-tips {
            margin-top: 20px;
            font-size: 12px;
            color: #999;
            text-align: center;
        }

        .login-input-icon {
            position: absolute;
            right: 16px;
            top: 40px;
            color: #999;
            font-size: 18px;
        }

        .login-form-input:focus + .login-input-icon {
            color: #ff3b30;
        }

        .login-pdd-logo {
            display: flex;
            justify-content: center;
            margin-bottom: 15px;
        }

        .login-pdd-logo span {
            font-size: 26px;
            font-weight: bold;
            color: white;
            letter-spacing: 1px;
        }

        /* 登录关闭按钮 */
        .login-close-btn {
            position: absolute;
            top: 15px;
            left: 15px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: white;
            font-size: 18px;
            z-index: 10;
            transition: all 0.3s;
        }

        .login-close-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        /* Toast提示样式 */
        .login-toast {
            position: fixed;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 1000;
            display: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            max-width: 80%;
            text-align: center;
        }

        .login-toast.shake {
            animation: login-shake 0.5s ease-in-out;
        }

        @keyframes login-shake {
            0%, 100% {
                transform: translateX(-50%);
            }
            10%, 30%, 50%, 70%, 90% {
                transform: translateX(calc(-50% - 5px));
            }
            20%, 40%, 60%, 80% {
                transform: translateX(calc(-50% + 5px));
            }
        }

        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 300;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 16px;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 轮播图 -->
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide">
                <img src="https://bugstack.cn/images/article/product/book/mybatis-03.png?raw=true" alt="手写MyBatis">
            </div>
            <div class="swiper-slide">
                <img src="https://bugstack.cn/images/article/product/book/mybatis-03.png?raw=true" alt="手写MyBatis">
            </div>
            <div class="swiper-slide">
                <img src="https://bugstack.cn/images/article/product/book/mybatis-03.png?raw=true" alt="手写MyBatis">
            </div>
        </div>
        <div class="swiper-indicator">
            <div class="swiper-dot active"></div>
            <div class="swiper-dot"></div>
            <div class="swiper-dot"></div>
        </div>
    </div>

    <!-- 商品信息 -->
    <div class="product-info">
        <h1 class="product-title" id="product-title">手写MyBatis：渐进式源码实践（全彩）</h1>
        <div class="promotion">
            <span class="promotion-tag">大促优惠</span>
            <span class="promotion-text" id="promotion-text">直降￥0，0人再抢，参与马上抢到</span>
        </div>
        <div class="price-section">
            <span class="current-price" id="current-price">￥0</span>
            <span class="original-price" id="original-price">￥0</span>
        </div>
    </div>

    <!-- 拼团信息 -->
    <div class="group-buy-section">
        <h2 class="section-title">拼单即将结束</h2>
        <div class="group-list" id="group-list">
            <!-- 团队列表将动态生成 -->
        </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
        <button class="action-btn">
            <span class="icon">❤</span>
            <span>收藏</span>
        </button>
        <button class="action-btn">
            <span class="icon">🛒</span>
            <span>购物车</span>
        </button>
        <div class="buy-btns">
            <button class="solo-buy" id="solo-buy">单独购买</button>
            <button class="group-buy" id="group-buy">开团购买</button>
        </div>
    </div>

    <!-- 支付页面 -->
    <div class="payment-page" id="payment-page">
        <div class="payment-header">请扫码支付</div>
        <div class="payment-amount" id="payment-amount">支付金额 ¥0</div>
        <div class="qrcode-container">
            <div class="qrcode-placeholder">
                <div>二维码</div>
                <div>(模拟支付界面)</div>
            </div>
        </div>
        <div class="payment-actions">
            <button class="cancel-btn" id="cancel-payment">取消支付</button>
            <button class="confirm-btn" id="confirm-payment">支付完成</button>
        </div>
    </div>

    <!-- 登录弹窗 -->
    <div class="login-overlay" id="login-overlay">
        <div class="login-container">
            <button class="login-close-btn" id="login-close-btn">×</button>
            <div class="login-header">
                <div class="login-pdd-logo">
                    <span>拼</span>
                    <span>多</span>
                    <span>多</span>
                </div>
                <h1 class="login-title">欢迎登录</h1>
                <p class="login-subtitle">小傅哥拼团</p>
            </div>

            <form class="login-form" id="login-form">
                <div class="login-form-group">
                    <label class="login-form-label" for="login-username">用户名</label>
                    <input type="text" id="login-username" class="login-form-input" placeholder="请输入用户名">
                    <span class="login-input-icon">👤</span>
                    <div class="login-form-error" id="login-username-error">用户名只能是中文、英文、数字的组合</div>
                </div>
                <div class="login-form-group">
                    <label class="login-form-label" for="login-password">密码</label>
                    <input type="password" id="login-password" class="login-form-input" placeholder="请输入6位数字密码">
                    <span class="login-input-icon">🔒</span>
                    <div class="login-form-error" id="login-password-error">密码必须是6位数字</div>
                </div>
                <button type="submit" class="login-btn">登录</button>
                <div class="login-tips">登录后即可参与拼团购买</div>
            </form>
        </div>
    </div>

    <!-- Toast提示 -->
    <div class="login-toast" id="login-toast"></div>

    <!-- 加载中提示 -->
    <div class="loading" id="loading">加载中...</div>
</div>

<script>
    // Cookie操作函数
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    // 检查登录状态
    function checkLogin() {
        return getCookie("user") !== null;
    }

    // 显示登录弹窗
    function showLoginOverlay() {
        document.getElementById('login-overlay').style.display = 'flex';
    }

    // 隐藏登录弹窗
    function hideLoginOverlay() {
        document.getElementById('login-overlay').style.display = 'none';
    }

    // 验证用户名格式
    function validateUsername(username) {
        const regex = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
        return regex.test(username);
    }

    // 验证密码格式
    function validatePassword(password) {
        const regex = /^\d{6}$/;
        return regex.test(password);
    }

    // 显示Toast提示
    function showLoginToast(message) {
        const toast = document.getElementById('login-toast');
        toast.textContent = message;
        toast.style.display = 'block';
        toast.classList.add('shake');

        // 3秒后隐藏Toast
        setTimeout(() => {
            toast.style.display = 'none';
            toast.classList.remove('shake');
        }, 3000);
    }

    // 将毫秒转换为HH:MM:SS格式
    function msToTime(ms) {
        if (!ms || ms <= 0) return "00:00:00";

        const seconds = Math.floor(ms / 1000);
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        return [
            hours.toString().padStart(2, '0'),
            minutes.toString().padStart(2, '0'),
            secs.toString().padStart(2, '0')
        ].join(':');
    }

    // 从毫秒转换为秒（用于倒计时）
    function msToSeconds(ms) {
        return Math.floor(ms / 1000);
    }

    // 请求API获取商品信息
    async function fetchGoodsInfo() {
        const userCookie = getCookie("user");
        let userId = "";

        if (userCookie) {
            try {
                const userData = JSON.parse(userCookie);
                userId = userData.username || "";
            } catch (e) {
                console.error("解析用户Cookie失败", e);
            }
        }

        const requestData = {
            userId: userId,
            goodsId: "9890001",
            source: "s01",
            channel: "c01"
        };

        try {
            const response = await fetch('http://127.0.0.1:8091/api/v1/group-buy-market/home-page/query_goods_group_buy_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });

            const data = await response.json();

            if (data.code === "E0000") {
                // 成功获取数据，更新页面
                updatePageWithData(data.data);
            } else {
                // 显示错误信息
                showLoginToast(data.info || "请求失败");
            }
        } catch (error) {
            console.error("API请求失败:", error);
            showLoginToast("网络错误，请稍后重试");

            // 如果API请求失败，使用模拟数据
            useMockData();
        }
    }

    // 使用模拟数据
    function useMockData() {
        const mockData = {
            goods: {
                goodsId: "9890001",
                originalPrice: 100.00,
                deductionPrice: 20,
                payPrice: 80.00,
                goodsName: "《手写MyBatis：渐进式源码实践》"
            },
            teamStatistic: {
                allTeamCount: 2,
                allTeamCompleteCount: 0,
                allTeamUserCount: 76
            },
            teamList: [
                {
                    teamId: "75218722",
                    teamName: "小傅哥",
                    groupBuyEndTime: 1922869180000,
                    groupBuyEndLeftTime: 349000,
                    groupBuyStartTime: 1733566780000,
                    targetCount: 3,
                    completeCount: 1,
                    lockCount: 0
                },
                {
                    teamId: "75218723",
                    teamName: "李二狗",
                    groupBuyEndTime: 1922869180000,
                    groupBuyEndLeftTime: 349000,
                    groupBuyStartTime: 1733566780000,
                    targetCount: 3,
                    completeCount: 1,
                    lockCount: 0
                }
            ]
        };

        updatePageWithData(mockData);
    }

    // 使用API返回的数据更新页面
    function updatePageWithData(data) {
        // 更新商品信息
        document.getElementById('product-title').textContent = data.goods.goodsName;
        document.getElementById('promotion-text').textContent = `直降￥${data.goods.deductionPrice}，${data.teamStatistic.allTeamUserCount}人再抢，参与马上抢到`;
        document.getElementById('current-price').textContent = `￥${data.goods.payPrice}`;
        document.getElementById('original-price').textContent = `￥${data.goods.originalPrice}`;
        document.getElementById('payment-amount').textContent = `支付金额 ¥${data.goods.payPrice}`;

        // 更新团队列表
        const groupList = document.getElementById('group-list');
        groupList.innerHTML = '';

        data.teamList.forEach((team, index) => {
            const teamItem = document.createElement('div');
            teamItem.className = 'group-item';

            // 获取名字的第一个字符作为头像
            const firstNameChar = team.teamName.charAt(0);

            teamItem.innerHTML = `
                    <div class="avatar">${firstNameChar}</div>
                    <div class="group-info">
                        <div class="group-name">${team.teamName}</div>
                        <div class="group-status">拼单即将结束</div>
                    </div>
                    <div class="group-action">
                        <div class="countdown" data-time="${msToSeconds(team.groupBuyEndLeftTime)}">${msToTime(team.groupBuyEndLeftTime)}</div>
                        <button class="join-btn" data-group="${team.teamId}">立即抢单</button>
                    </div>
                `;

            groupList.appendChild(teamItem);
        });

        // 重新绑定事件到新创建的按钮
        bindJoinButtons();
    }

    // 绑定立即抢单按钮事件
    function bindJoinButtons() {
        const joinButtons = document.querySelectorAll('.join-btn');
        joinButtons.forEach(button => {
            button.addEventListener('click', function () {
                checkLoginAndProceed(() => {
                    const groupId = this.getAttribute('data-group');
                    showLoading();

                    mockApiRequest('http://127.0.0.1/market/3', {groupId: groupId})
                        .then(result => {
                            hideLoading();
                            if (result.success) {
                                showPaymentPage();
                            } else {
                                alert('抢单失败，请重试');
                            }
                        });
                });
            });
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        // 轮播图逻辑
        const swiperWrapper = document.querySelector('.swiper-wrapper');
        const swiperDots = document.querySelectorAll('.swiper-dot');
        let currentIndex = 0;

        function updateSwiper() {
            swiperWrapper.style.transform = `translateX(-${currentIndex * 100}%)`;

            swiperDots.forEach((dot, index) => {
                dot.classList.toggle('active', index === currentIndex);
            });
        }

        // 自动轮播
        setInterval(() => {
            currentIndex = (currentIndex + 1) % 3;
            updateSwiper();
        }, 3000);

        // 倒计时逻辑
        function updateCountdowns() {
            const countdownElements = document.querySelectorAll('.countdown');

            countdownElements.forEach(element => {
                let time = parseInt(element.getAttribute('data-time'));
                if (time > 0) {
                    time--;
                    element.setAttribute('data-time', time);
                    element.textContent = msToTime(time * 1000);
                } else {
                    element.textContent = '已结束';
                    element.style.color = '#999';
                }
            });
        }

        setInterval(updateCountdowns, 1000);

        // 按钮事件处理
        const soloBuyButton = document.getElementById('solo-buy');
        const groupBuyButton = document.getElementById('group-buy');
        const paymentPage = document.getElementById('payment-page');
        const cancelPaymentButton = document.getElementById('cancel-payment');
        const confirmPaymentButton = document.getElementById('confirm-payment');
        const loginOverlay = document.getElementById('login-overlay');
        const loginForm = document.getElementById('login-form');
        const loginCloseBtn = document.getElementById('login-close-btn');
        const loading = document.getElementById('loading');

        // 显示加载提示
        function showLoading() {
            loading.style.display = 'flex';
        }

        // 隐藏加载提示
        function hideLoading() {
            loading.style.display = 'none';
        }

        // 模拟API请求
        function mockApiRequest(url, data = null) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    console.log(`请求API: ${url}`, data);
                    resolve({success: true, message: '操作成功'});
                }, 1000);
            });
        }

        // 显示支付页面
        function showPaymentPage() {
            paymentPage.style.display = 'flex';
        }

        // 隐藏支付页面
        function hidePaymentPage() {
            paymentPage.style.display = 'none';
        }

        // 检查登录状态并执行操作
        function checkLoginAndProceed(callback) {
            if (checkLogin()) {
                callback();
            } else {
                showLoginOverlay();
            }
        }

        // 绑定立即抢单按钮事件
        bindJoinButtons();

        // 单独购买按钮点击事件
        soloBuyButton.addEventListener('click', function () {
            checkLoginAndProceed(() => {
                showPaymentPage();
            });
        });

        // 开团购买按钮点击事件
        groupBuyButton.addEventListener('click', function () {
            checkLoginAndProceed(() => {
                showLoading();

                mockApiRequest('http://127.0.0.1/market/3')
                    .then(result => {
                        hideLoading();
                        if (result.success) {
                            showPaymentPage();
                        } else {
                            alert('开团失败，请重试');
                        }
                    });
            });
        });

        // 取消支付按钮点击事件
        cancelPaymentButton.addEventListener('click', function () {
            hidePaymentPage();
        });

        // 支付完成按钮点击事件
        confirmPaymentButton.addEventListener('click', function () {
            showLoading();

            mockApiRequest('http://127.0.0.1/market/4')
                .then(result => {
                    hideLoading();
                    hidePaymentPage();
                    if (result.success) {
                        alert('支付成功！');
                    } else {
                        alert('支付失败，请重试');
                    }
                });
        });

        // 登录关闭按钮点击事件
        loginCloseBtn.addEventListener('click', function () {
            hideLoginOverlay();
        });

        // 登录表单提交事件
        loginForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const loginUsername = document.getElementById('login-username').value;
            const loginPassword = document.getElementById('login-password').value;
            let isValid = true;
            let errorMessage = '';

            // 验证用户名
            if (!loginUsername) {
                errorMessage = '请输入用户名';
                isValid = false;
            } else if (!validateUsername(loginUsername)) {
                errorMessage = '用户名只能是中文、英文、数字的组合';
                isValid = false;
            } else {
                document.getElementById('login-username-error').style.display = 'none';
            }

            // 验证密码
            if (!loginPassword) {
                if (errorMessage) {
                    errorMessage = '请输入用户名和密码';
                } else {
                    errorMessage = '请输入密码';
                }
                isValid = false;
            } else if (!validatePassword(loginPassword)) {
                if (errorMessage) {
                    errorMessage = '用户名格式错误，密码必须是6位数字';
                } else {
                    errorMessage = '密码必须是6位数字';
                }
                isValid = false;
            } else {
                document.getElementById('login-password-error').style.display = 'none';
            }

            if (!isValid) {
                // 显示Toast提示
                showLoginToast(errorMessage);
                return;
            }

            // 保存登录信息到cookie
            setCookie('user', JSON.stringify({username: loginUsername}), 7);

            // 隐藏登录弹窗
            hideLoginOverlay();

            // 重新获取商品信息
            showLoading();
            fetchGoodsInfo().finally(() => {
                hideLoading();
            });

            // 显示成功提示
            showLoginToast('登录成功！');
        });

        // 点击登录弹窗外部关闭弹窗
        loginOverlay.addEventListener('click', function (e) {
            if (e.target === loginOverlay) {
                hideLoginOverlay();
            }
        });

        // 输入时实时验证
        document.getElementById('login-username').addEventListener('input', function () {
            if (validateUsername(this.value)) {
                document.getElementById('login-username-error').style.display = 'none';
            }
        });

        document.getElementById('login-password').addEventListener('input', function () {
            if (validatePassword(this.value)) {
                document.getElementById('login-password-error').style.display = 'none';
            }
        });

        // 初始加载数据
        showLoading();
        fetchGoodsInfo().finally(() => {
            hideLoading();
        });
    });
</script>
</body>
</html>